﻿using System;
using System.Collections.Generic;
using TCKQKL.Service.DataContract;
using TCKQKL.FrontEnd.DataModel;
using StockTrader.BusinessService.DataContract.Hastc;
using StockTrader.FrontEnd.DataContract;
using StockTrader.BusinessService.DataContract;
using StockTrader.BusinessService.DataContract.Structure;
using StockTrader.BusinessService.DataContract.Mortgate;
using Mortgage.DAL;
using Mortgage.DDL;

namespace LoanMonitor.Business
{
    public class DALclient
    {
        LookupServiceDAL ls_dal = new LookupServiceDAL();
        MortgageMornitorDAL m_dal = new MortgageMornitorDAL();

        #region LookupService
        public DateTime getTradingDate()
        {
            try
            {
                return ls_dal.getTradingDate();
            }
            catch
            {
                throw;
            }
        }
        public List<OrdersBoscDataUI> getOrders(decimal investorID)
        {
            try
            {

                List<OrdersBoscModel> orderModel = ls_dal.getOrders(investorID);
                if (orderModel == null)
                    return null;
                List<OrdersBoscDataUI> orderUI = new List<OrdersBoscDataUI>();
                foreach (OrdersBoscModel order in orderModel)
                {
                    orderUI.Add(new OrdersBoscDataUI(order.orderID, order.orderSide, order.orderType, order.orderClass, order.orderStatus, order.openDate, order.symbol, order.quantity, order.price, order.orderFee, order.orderOrigin));
                }

                return orderUI;
            }
            catch
            {
                throw;
            }
        }
        public List<OrdersBoscDataUI> getOrdersWaiting(decimal investorID)
        {
            try
            {

                List<OrdersBoscModel> orderModel = ls_dal.getOrdersWaiting(investorID);
                if (orderModel == null)
                    return null;
                List<OrdersBoscDataUI> orderUI = new List<OrdersBoscDataUI>();
                foreach (OrdersBoscModel order in orderModel)
                {
                    orderUI.Add(new OrdersBoscDataUI(order.orderID, order.orderSide, order.orderType, order.orderClass, order.orderStatus, order.openDate, order.symbol, order.quantity, order.price, order.orderFee, order.orderOrigin));
                }

                return orderUI;
            }
            catch
            {
                throw;
            }
        }
        public List<OrdersBoscDataUI> getOrdersHistoryDetail(decimal investorID, DateTime fromDate, DateTime toDate, string orderType, string orderClass, string orderSide, string symbol, string ID, decimal priceLow, decimal priceHigh, decimal qttyLow, decimal qttyHigh)
        {
            try
            {

                List<OrdersBoscModel> orderModel = ls_dal.getOrdersHistoryDetail(investorID, fromDate, toDate, orderType, orderClass, orderSide, symbol, ID, priceLow, priceHigh, qttyLow, qttyHigh);
                if (orderModel == null)
                    return null;
                List<OrdersBoscDataUI> orderUI = new List<OrdersBoscDataUI>();
                foreach (OrdersBoscModel order in orderModel)
                {
                    orderUI.Add(new OrdersBoscDataUI(order.orderID, order.orderSide, order.orderType, order.orderClass, order.orderStatus, order.openDate, order.symbol, order.quantity, order.price, order.orderFee, order.orderOrigin));
                }

                return orderUI;
            }
            catch
            {
                throw;
            }
        }
        public List<OrdersBoscDataUI> getOrdersTopN(decimal investorID, int topN)
        {
            try
            {

                List<OrdersBoscModel> orderModel = ls_dal.getOrdersTopN(investorID, topN);
                if (orderModel == null)
                    return null;
                List<OrdersBoscDataUI> orderUI = new List<OrdersBoscDataUI>();
                foreach (OrdersBoscModel order in orderModel)
                {
                    orderUI.Add(new OrdersBoscDataUI(order.orderID, order.orderSide, order.orderType, order.orderClass, order.orderStatus, order.openDate, order.symbol, order.quantity, order.price, order.orderFee, order.orderOrigin));
                }

                return orderUI;
            }
            catch
            {
                throw;
            }
        }
        public List<AccountDataUI> getAccountByInvestorId(decimal investorID)
        {
            try
            {
                List<AccountDataModel> accounts = ls_dal.getAccountByInvestorID(investorID);
                if (accounts == null)
                    return null;
                List<AccountDataUI> accountUI = new List<AccountDataUI>();
                foreach (AccountDataModel account in accounts)
                {
                    if ((account.tradingAmount > 0) || (account.nettingAmount > 0) || (account.lockedAmount > 0))
                    {
                        QuoteDataUI quote = getQuote(account.stockId.Trim());
                        if (quote != null)
                            accountUI.Add(new AccountDataUI(account.stockId, account.stockName, account.tradingAmount, account.trustedAmount, account.nettingAmount, account.lockedAmount, account.
    lastModified, quote.Ref));

                    }
                }

                return accountUI;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public List<BankDataUI> getBankDataByInvestorId(decimal investorID)
        {
            try
            {
                List<BankDataUI> bankUIs = new List<BankDataUI>();
                List<BankDataModel> banks = ls_dal.getBankByInvestorID(investorID);

                if (banks.Count.Equals(0))
                    bankUIs.Add(new BankDataUI("VND", "VND", 0, 0, 0, 0, DateTime.Now, DateTime.Now));

                foreach (BankDataModel bankModel in banks)
                {
                    decimal remainStart = getRemain(investorID, getTradingDate());
                    decimal blockAmount = 0;
                    BankDataUI temp = getBankDataByDate(investorID, DateTime.Now.Date);
                    if (temp != null)
                        blockAmount = temp.blockAmount;// getBankDataByDate(investorID, DateTime.Now.Date).blockAmount;

                    decimal tradingAmount = remainStart;
                    foreach (TransDataUI tran in getTransByInvestorID(investorID, getTradingDate(), getTradingDate()))
                    {
                        if (tran.IncreaseAmount > 0)
                        {
                            tradingAmount += tran.IncreaseAmount;
                        }
                        else
                            if (tran.DecreaseAmount > 0)
                            {
                                tradingAmount -= tran.DecreaseAmount;
                            }

                    }
                    bankUIs.Add(new BankDataUI(bankModel.bankAccount, bankModel.bankName, tradingAmount - blockAmount, bankModel.trustedAmount, bankModel.nettingAmount, blockAmount, bankModel.openDate, bankModel.lastModified));
                }
                return bankUIs;
            }
            catch
            {
                throw;
            }
        }
        public BankDataUI getBankDataByDate(decimal investorID, DateTime selected)
        {
            try
            {
                BankDataModel bank = ls_dal.getBankDataByDate(investorID, selected);
                if (bank == null)
                    return null;
                return new BankDataUI(bank.bankAccount, bank.bankName, bank.tradingAmount, bank.trustedAmount, bank.nettingAmount, bank.blockAmount, bank.openDate, bank.lastModified);
            }
            catch
            {
                throw;
            }

        }

        public List<MatchResultUI> getMatchedResult(decimal investorID)
        {
            try
            {

                List<MatchedResultModel> matchs = ls_dal.getMatchedResult(investorID);
                if (matchs == null)
                    return null;
                List<MatchResultUI> results = new List<MatchResultUI>();
                foreach (MatchedResultModel result in matchs)
                {
                    results.Add(new MatchResultUI(result.confirmNo, result.stockCode, result.stockQtty, result.price, result.feeAmount, result.orderID, result.transDate, result.TransType));
                }

                return results;
            }
            catch
            {
                throw;
            }
        }
        public List<MatchResultUI> getMatchedResultTopN(decimal investorID, int topN)
        {
            try
            {

                List<MatchedResultModel> matchs = ls_dal.getMatchedResultTopN(investorID, topN);
                if (matchs == null)
                    return null;
                List<MatchResultUI> results = new List<MatchResultUI>();
                foreach (MatchedResultModel result in matchs)
                {
                    results.Add(new MatchResultUI(result.confirmNo, result.stockCode, result.stockQtty, result.price, result.feeAmount, result.orderID, result.transDate, result.TransType));
                }

                return results;
            }
            catch
            {
                throw;
            }
        }
        public List<MatchResultUI> getMatchedResultEarlyByAccountNo(string accountNo)
        {
            try
            {

                List<MatchedResultModel> matchs = ls_dal.getMatchedResultEarlyByAccountNo(accountNo);
                if (matchs == null)
                    return null;
                List<MatchResultUI> results = new List<MatchResultUI>();
                foreach (MatchedResultModel result in matchs)
                {
                    results.Add(new MatchResultUI(result.confirmNo, result.stockCode, result.stockQtty, result.price, result.feeAmount, result.orderID, result.transDate, result.TransType));
                }

                return results;
            }
            catch
            {
                throw;
            }
        }
        public List<OrdersBoscDataUI> getOrdersHistory(decimal investorID, DateTime start, DateTime end)
        {
            try
            {

                List<OrdersBoscModel> orders = ls_dal.getOrdersHistory(investorID, start, end);
                if (orders == null)
                    return null;
                List<OrdersBoscDataUI> ordersUI = new List<OrdersBoscDataUI>();
                foreach (OrdersBoscModel order in orders)
                {
                    ordersUI.Add(new OrdersBoscDataUI(order.orderID, order.orderSide, order.orderType, order.orderClass, order.orderStatus, order.openDate, order.symbol, order.quantity, order.price, order.orderFee, order.orderOrigin));
                }

                return ordersUI;
            }
            catch
            {
                throw;
            }
        }
        public List<OrdersBoscDataUI> getOrdersRelatedHistoryByOrderId(string originalOrderID)
        {
            try
            {
                List<OrdersBoscModel> orders = ls_dal.getOrdersRelatedHistoryByOrderId(originalOrderID);
                if (orders == null)
                    return null;
                List<OrdersBoscDataUI> ordersUI = new List<OrdersBoscDataUI>();
                foreach (OrdersBoscModel order in orders)
                {
                    ordersUI.Add(new OrdersBoscDataUI(order.orderID, order.orderSide, order.orderType, order.orderClass, order.orderStatus, order.openDate, order.symbol, order.quantity, order.price, order.orderFee, order.orderOrigin));
                }

                return ordersUI;
            }
            catch
            {
                throw;
            }
        }
        public List<TransDataUI> getTransByInvestorID(decimal investorID, DateTime fromDate, DateTime toDate)
        {
            try
            {
                List<TransDataModel> trans = ls_dal.getTransByInvestorId(investorID, fromDate, toDate);
                if (trans == null)
                    return null;
                decimal remain = getRemain(investorID, fromDate);
                List<TransDataUI> transUI = new List<TransDataUI>();
                foreach (TransDataModel tran in trans)
                {
                    if (tran.IncreaseAmount > 0)
                    {
                        remain += tran.IncreaseAmount;
                        transUI.Add(new TransDataUI(tran.Id, tran.Date, tran.TransText, tran.Code, tran.IncreaseQtty, tran.IncreaseAmount, tran.DecreaseQtty, tran.DecreaseAmount, remain, tran.Note));
                    }
                    else
                        if (tran.DecreaseAmount > 0)
                        {
                            remain -= tran.DecreaseAmount;
                            transUI.Add(new TransDataUI(tran.Id, tran.Date, tran.TransText, tran.Code, tran.IncreaseQtty, tran.IncreaseAmount, tran.DecreaseQtty, tran.DecreaseAmount, remain, tran.Note));
                        }
                        else
                            transUI.Add(new TransDataUI(tran.Id, tran.Date, tran.TransText, tran.Code, tran.IncreaseQtty, tran.IncreaseAmount, tran.DecreaseQtty, tran.DecreaseAmount, remain, tran.Note));

                }
                return transUI;
            }
            catch
            {
                throw;
            }
        }
        public decimal getRemain(decimal investorID, DateTime fromDate)
        {
            try
            {
                return ls_dal.getRemain(investorID, fromDate);
            }
            catch
            {
                throw;
            }
        }
        public decimal getNettingAmountByInvestorId(decimal investorID)
        {
            try
            {
                return ls_dal.getNettingAmountByInvestorId(investorID);
            }
            catch
            {
                throw;
            }

        }

        public List<OrdersBoscDataUI> getOrdersRelatedByOrderId(string originOrderID)
        {
            try
            {

                List<OrdersBoscModel> orders = ls_dal.getOrdersRelatedByOrderId(originOrderID);
                if (orders == null)
                    return null;
                List<OrdersBoscDataUI> ordersUI = new List<OrdersBoscDataUI>();
                foreach (OrdersBoscModel order in orders)
                {
                    ordersUI.Add(new OrdersBoscDataUI(order.orderID, order.orderSide, order.orderType, order.orderClass, order.orderStatus, order.openDate, order.symbol, order.quantity, order.price, order.orderFee, order.orderOrigin));
                }

                return ordersUI;
            }
            catch
            {
                throw;
            }

        }
        public List<MatchResultUI> getMatchedResultByOrderID(string orderID)
        {
            try
            {

                List<MatchedResultModel> matchs = ls_dal.getMatchedResultByOrderID(orderID);
                if (matchs == null)
                    return null;
                List<MatchResultUI> results = new List<MatchResultUI>();
                foreach (MatchedResultModel result in matchs)
                {
                    results.Add(new MatchResultUI(result.confirmNo, result.stockCode, result.stockQtty, result.price, result.feeAmount, result.orderID, result.transDate, result.TransType));
                }

                return results;
            }
            catch
            {
                throw;
            }

        }
        public List<MatchResultUI> getMatchedResultByInvestor(decimal investorID)
        {
            try
            {

                List<MatchedResultModel> matchs = ls_dal.getMatchedResultByInvestorId(investorID);
                if (matchs == null)
                    return null;
                List<MatchResultUI> results = new List<MatchResultUI>();
                foreach (MatchedResultModel result in matchs)
                {
                    results.Add(new MatchResultUI(result.confirmNo, result.stockCode, result.stockQtty, result.price, result.feeAmount, result.orderID, result.transDate, result.TransType));
                }

                return results;
            }
            catch
            {
                throw;
            }

        }
        public List<OrdersBoscDataUI> getOrderCompleted(decimal investorID)
        {
            return null;
        }
        public InvestorDataUI getAccountData(string accountNo)
        {
            try
            {
                InvestorDataModel investor = ls_dal.getAccountData(accountNo);
                if (investor == null)
                    return null;

                return new InvestorDataUI(investor.investorId, investor.accountNo, investor.investorId.ToString());
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public List<InvestorDataUI> getAssignAccountsByInvestorId(decimal investorID)
        {
            List<InvestorDataUI> investors = new List<InvestorDataUI>();
            try
            {
                List<InvestorDataModel> members = ls_dal.getAssignInvestorData(investorID);
                if (investors == null)
                    return null;
                foreach (InvestorDataModel member in members)
                {
                    InvestorDataUI investor = new InvestorDataUI(member.investorId, member.accountNo, member.investorId.ToString());
                    investors.Add(investor);
                }
                return investors;
            }
            catch
            {
                throw;
            }

        }
        public InvestorDataProfileUI getAccountProfileData(decimal investorID)
        {
            try
            {
                InvestorDataProfileModel investor = ls_dal.getAccountProfileData(investorID);
                if (investor == null)
                    return null;

                return new InvestorDataProfileUI(investor.accountNo, investor.name, investor.address, investor.birthday, investor.address, investor.phone, investor.ServiceRegisterd);
            }
            catch
            {
                throw;
            }
        }
        public InvestorDataUI loginProcess(string accountNo, string password)
        {
            try
            {
                InvestorDataModel investor = ls_dal.loginProcess(accountNo, password);
                if (investor == null)
                    return null;

                return new InvestorDataUI(investor.investorId, investor.accountNo, investor.bankAccount);
            }
            catch
            {
                throw;
            }
        }
        public void logout(string accountNo)
        {
            try
            {

                ls_dal.logout(accountNo);

            }
            catch
            {
                throw;
            }

        }
        public QuoteDataUI getQuote(string symbol)
        {
            try
            {

                StocksDataModel myquote = ls_dal.getQuote(symbol);
                if (myquote == null)
                    return null;

                return new QuoteDataUI(myquote.Symbol, myquote.CompanyName, myquote.Closed, myquote.Open, myquote.Low, myquote.High, myquote.Changed, myquote.Volume, myquote.Ceiling, myquote.Floor, myquote.Closed, myquote.exCenter);
            }
            catch
            {
                throw;
            }
        }

        public QuoteDataUI getQuoteAvg(string symbol, bool isAvg)
        {
            try
            {

                StocksDataModel myquote = ls_dal.getQuoteAvg(symbol, isAvg);
                if (myquote == null)
                    return null;

                return new QuoteDataUI(myquote.Symbol, myquote.CompanyName, myquote.Closed, myquote.Open, myquote.Low, myquote.High, myquote.Changed, myquote.Volume, myquote.Ceiling, myquote.Floor, myquote.Closed, myquote.exCenter);
            }
            catch
            {
                throw;
            }
        }

        public MarketSummaryDataUI getMaretSummary(string marketName)
        {
            try
            {

                MarketSummaryDataModel market = ls_dal.getMarketSummary(marketName);
                if (market == null)
                    return null;

                return new MarketSummaryDataUI(market.marketName, market.index, market.Changed, market.totalTrade, market.totalShare, market.totalValue, null, null, null, null, null, null, market.summaryDate, market.MarketStatus);
            }
            catch
            {
                throw;
            }
        }

        public List<TradingResultUI> getTradingResult(decimal investorID)
        {
            List<TradingResultUI> results = new List<TradingResultUI>();
            List<OrdersBoscDataUI> orders = new List<OrdersBoscDataUI>();
            try
            {
                orders = getOrdersWaiting(investorID);
                if (orders == null)
                    return null;
                foreach (OrdersBoscDataUI order in orders)
                {
                    TradingResultUI result = new TradingResultUI();
                    result.RootOrder = order;
                    result.RelatedOrders = getOrdersRelatedByOrderId(order.orderID);
                    result.DetailMatched = getMatchedResultByOrderID(order.orderID);
                    result.Symbol = order.symbol;
                    result.Side = order.OrderSide;
                    foreach (MatchResultUI match in result.DetailMatched)
                    {
                        result.SubQtty += match.stockQtty;
                        result.FeeAmount += match.feeAmount;
                        result.SubValue += match.price * match.stockQtty;
                    }
                    if (order.OrderSide.Equals("Mua"))
                        result.SubValue = result.SubValue + result.FeeAmount;
                    else
                        result.SubValue = result.SubValue - result.FeeAmount;
                    if (result.SubQtty > 0)
                        results.Add(result);
                }
                return results;
            }
            catch
            {
                throw;
            }
        }
        public List<TradingResultUI> getTradingResultHistory(decimal investorID, DateTime fromDate, DateTime toDate, string orderType, string orderClass, string orderSide, string symbol, string ID, decimal priceLow, decimal priceHigh, decimal qttyLow, decimal qttyHigh)
        {
            List<TradingResultUI> results = new List<TradingResultUI>();
            List<OrdersBoscDataUI> orders = new List<OrdersBoscDataUI>();
            try
            {
                orders = getOrdersHistoryDetail(investorID, fromDate, toDate, orderType, orderClass, orderSide, symbol, ID, priceLow, priceHigh, qttyLow, qttyHigh);
                if (orders == null)
                    return null;
                foreach (OrdersBoscDataUI order in orders)
                {
                    TradingResultUI result = new TradingResultUI();
                    result.RootOrder = order;
                    //result.RelatedOrders = getOrdersRelatedHistoryByOrderId(order.orderID);
                    result.DetailMatched = getMatchedResultByOrderID(order.orderID);
                    result.Symbol = order.symbol;
                    result.Side = order.OrderSide;
                    foreach (MatchResultUI match in result.DetailMatched)
                    {
                        result.SubQtty += match.stockQtty;
                        result.FeeAmount += match.feeAmount;
                        result.SubValue += match.price * match.stockQtty;
                    }
                    if (order.OrderSide.Equals("Mua"))
                        result.SubValue = result.SubValue + result.FeeAmount;
                    else
                        result.SubValue = result.SubValue - result.FeeAmount;

                    switch (orderType)
                    {
                        case "MATCHED":
                            if (result.SubQtty > 0)
                                results.Add(result);
                            break;
                        default:
                            results.Add(result);
                            break;
                    }
                }
                return results;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public List<HoldingDataUI> getHolding(decimal investorID)
        {
            List<HoldingDataUI> holdings = new List<HoldingDataUI>();
            List<AccountDataUI> accounts = new List<AccountDataUI>();
            try
            {
                accounts = getAccountByInvestorId(investorID);
                if (accounts == null)
                    return null;
                foreach (AccountDataUI account in accounts)
                {
                    HoldingDataUI holding = new HoldingDataUI();
                    holding.Account = account;
                    holding.Quotes = getQuote(account.stockId);

                    if (holding.Quotes != null)
                        holdings.Add(holding);
                }
                return holdings;
            }
            catch
            {
                throw;
            }
        }
        public TotalHoldingDataUI getTotalHolding(decimal investorID)
        {
            List<HoldingDataUI> holdingList = getHolding(investorID);
            if (holdingList == null)
                return null;
            TotalHoldingDataUI totalHolding = new TotalHoldingDataUI();
            try
            {
                totalHolding.Holding = holdingList;
                totalHolding.AccountProfile = getAccountProfileData(investorID);
                totalHolding.BankData = getBankDataByInvestorId(investorID);
                foreach (HoldingDataUI holding in holdingList)
                {
                    totalHolding.TradingValue += holding.Account.tradingAmount * holding.Quotes.Closed * 1000;
                    totalHolding.NettingValue += holding.Account.nettingAmount * holding.Quotes.Closed * 1000;
                    totalHolding.LockedValue += holding.Account.lockedAmount * holding.Quotes.Closed * 1000;
                    totalHolding.TotalGain += holding.Gain;
                }
                totalHolding.TotalValue = (totalHolding.TradingValue + totalHolding.NettingValue) * 1000;
                return totalHolding;
            }
            catch
            {
                throw;
            }
        }
        public PersonalHoldingUI getPersonalHolding(decimal investorID)
        {
            PersonalHoldingUI personal = new PersonalHoldingUI();
            try
            {
                personal.MainAccount = getTotalHolding(investorID);
                if (personal.MainAccount == null)
                    return null;
                personal.TradingValue += personal.MainAccount.TradingValue;
                personal.NettingValue += personal.MainAccount.NettingValue;
                personal.LockedValue += personal.MainAccount.LockedValue;
                personal.TotalValue += personal.MainAccount.TotalValue;
                personal.TotalGain += personal.MainAccount.TotalGain;

                List<InvestorDataUI> assignInvestors = getAssignAccountsByInvestorId(investorID);
                personal.AssignAccounts = new List<TotalHoldingDataUI>();
                foreach (InvestorDataUI investor in assignInvestors)
                {
                    TotalHoldingDataUI totalHolding = new TotalHoldingDataUI();
                    totalHolding = getTotalHolding(investor.investorId);
                    personal.AssignAccounts.Add(totalHolding);

                    personal.TradingValue += totalHolding.TradingValue;
                    personal.NettingValue += totalHolding.NettingValue;
                    personal.LockedValue += totalHolding.LockedValue;
                    personal.TotalValue += totalHolding.TotalValue;
                    personal.TotalGain += totalHolding.TotalGain;
                }
                return personal;
            }
            catch
            {
                throw;
            }
        }
        public TotalTradingResultUI getTotalTradingResult(decimal investorID)
        {
            TotalTradingResultUI totalResult = new TotalTradingResultUI();
            try
            {
                totalResult.InvestorProfile = getAccountProfileData(investorID);
                totalResult.TradingResults = getTradingResult(investorID);
                foreach (TradingResultUI result in totalResult.TradingResults)
                {
                    totalResult.TotalValue += result.SubValue;
                    totalResult.TotalFee += result.FeeAmount;
                }
                return totalResult;
            }
            catch
            {
                throw;
            }
        }

        public TotalTradingResultUI getTotalTradingResultHistory(decimal investorID, DateTime fromDate, DateTime toDate, string orderType, string orderClass, string orderSide, string symbol, string ID, decimal priceLow, decimal priceHigh, decimal qttyLow, decimal qttyHigh)
        {
            TotalTradingResultUI totalResult = new TotalTradingResultUI();
            try
            {
                totalResult.InvestorProfile = getAccountProfileData(investorID);
                totalResult.TradingResults = getTradingResultHistory(investorID, fromDate, toDate, orderType, orderClass, orderSide, symbol, ID, priceLow, priceHigh, qttyLow, qttyHigh);
                foreach (TradingResultUI result in totalResult.TradingResults)
                {
                    totalResult.TotalValue += result.SubValue;
                    totalResult.TotalFee += result.FeeAmount;
                }
                return totalResult;
            }
            catch
            {
                throw;
            }
        }

        public PersonalTradingResultUI getPersonalTradingResult(decimal investorID, bool assignAccount)
        {
            PersonalTradingResultUI personal = new PersonalTradingResultUI();
            try
            {
                personal.MainTradingResult = getTotalTradingResult(investorID);
                personal.TotalValue += personal.MainTradingResult.TotalValue;
                personal.TotalFee += personal.MainTradingResult.TotalFee;

                List<InvestorDataUI> assignInvestors = getAssignAccountsByInvestorId(investorID);
                personal.AssignTradingResult = new List<TotalTradingResultUI>();
                foreach (InvestorDataUI investor in assignInvestors)
                {
                    TotalTradingResultUI tradingResult = new TotalTradingResultUI();
                    if (assignAccount)
                    {
                        tradingResult = getTotalTradingResult(investor.investorId);
                        personal.AssignTradingResult.Add(tradingResult);

                        personal.TotalValue += tradingResult.TotalValue;
                        personal.TotalFee += tradingResult.TotalFee;
                    }
                }
                return personal;
            }
            catch
            {
                throw;
            }
        }
        public PersonalTradingResultUI getPersonalTradingResultHistory(decimal investorID, DateTime fromDate, DateTime toDate, string orderType, string orderClass, string orderSide, string symbol, string ID, decimal priceLow, decimal priceHigh, decimal qttyLow, decimal qttyHigh, bool assignAccount)
        {
            PersonalTradingResultUI personal = new PersonalTradingResultUI();
            try
            {
                personal.MainTradingResult = getTotalTradingResultHistory(investorID, fromDate, toDate, orderType, orderClass, orderSide, symbol, ID, priceLow, priceHigh, qttyLow, qttyHigh);
                personal.TotalValue += personal.MainTradingResult.TotalValue;
                personal.TotalFee += personal.MainTradingResult.TotalFee;

                if (assignAccount)
                {
                    List<InvestorDataUI> assignInvestors = getAssignAccountsByInvestorId(investorID);
                    personal.AssignTradingResult = new List<TotalTradingResultUI>();
                    foreach (InvestorDataUI investor in assignInvestors)
                    {
                        TotalTradingResultUI tradingResult = new TotalTradingResultUI();
                        tradingResult = getTotalTradingResultHistory(investor.investorId, fromDate, toDate, orderType, orderClass, orderSide, symbol, ID, priceLow, priceHigh, qttyLow, qttyHigh);
                        personal.AssignTradingResult.Add(tradingResult);

                        personal.TotalValue += tradingResult.TotalValue;
                        personal.TotalFee += tradingResult.TotalFee;
                    }
                }
                else
                {
                    personal.AssignTradingResult = null;
                }
                return personal;
            }
            catch
            {
                throw;
            }
        }

        public List<DateTime> getBackDate()
        {
            try
            {
                return ls_dal.getBackDate();
            }
            catch
            {
                throw;
            }
        }
        public decimal getPreLoanByInvestor(decimal investorid)
        {
            try
            {
                return ls_dal.getPreLoanByInvestor(investorid);
            }
            catch
            {
                throw;
            }
        }



        private SortedList<int, SecuritiesInfo> stocks = new SortedList<int, SecuritiesInfo>();

        public List<OrderUI> getHoseOrders()
        {
            try
            {
                MortgageMornitorDAL dac = new MortgageMornitorDAL();
                List<OrderUI> list = new List<OrderUI>();

                List<OrderNewData> OrderNew = dac.getNewConditionedOrderData();
                List<OrderChangeData> OrderChange = dac.getOrderChangeData();
                List<OrderCancelData> OrderCancel = dac.getOrderCancelData();

                List<ConfirmOrderChangeData> ConfirmChange = dac.getConfirmOrderChangeData();
                List<ConfirmCrossingDealData> ConfirmCross = dac.getConfirmCrossingDealData();
                List<ConfirmDealData> ConfirmDeal = dac.getConfirmDealData();
                List<ConfirmOrderCancelData> ConfirmCancel = dac.getConfirmOrderCancelData();
                List<ConfirmOrderNewData> ConfirmNewOrder = dac.getConfirmOrderNewData();

                List<ConfirmDealData> cross = new List<ConfirmDealData>();
                foreach (ConfirmCrossingDealData cr in ConfirmCross)
                {
                    ConfirmDealData confirm = new ConfirmDealData();
                    confirm.TimeStamp = cr.Timestamp;
                    confirm.OrderNumber = cr.OrderNumberB;
                    confirm.Side = "B";
                    confirm.MatchedPrice = cr.Price;
                    confirm.MatchedVolume = cr.Volume;
                    confirm.CouterAccount = cr.OrderNumberS;
                    confirm.ConfirmNumber = cr.ConfirmNumber;
                    cross.Add(confirm);
                }
                foreach (ConfirmCrossingDealData cr in ConfirmCross)
                {
                    ConfirmDealData confirm = new ConfirmDealData();
                    confirm.TimeStamp = cr.Timestamp;
                    confirm.OrderNumber = cr.OrderNumberS;
                    confirm.Side = "S";
                    confirm.MatchedPrice = cr.Price;
                    confirm.MatchedVolume = cr.Volume;
                    confirm.CouterAccount = cr.OrderNumberB;
                    confirm.ConfirmNumber = cr.ConfirmNumber;
                    cross.Add(confirm);
                }


                foreach (OrderNewData order in OrderNew)
                {
                    OrderUI ui = new OrderUI();
                    List<OrderMatchedUI> dealList = new List<OrderMatchedUI>();
                    List<HoseOrderChangeUI> changeList = new List<HoseOrderChangeUI>();

                    ui.Time = order.TimeStamp.Substring(0, 2) + ":" + order.TimeStamp.Substring(2, 2) + ":" + order.TimeStamp.Substring(4, 2);
                    ui.OrderNo = order.OrderNumber;
                    ui.AccountNo = order.ClientID;
                    ui.Side = (order.Side.Equals("S")) ? "BÁN" : "MUA";
                    ui.Symbol = order.Symbol.Trim();
                    ui.Volume = order.Volume;
                    ui.Price = order.Price.Trim();
                    ui.Status = string.Empty;
                    ui.Market = "HOSE";

                    foreach (ConfirmDealData dl in ConfirmDeal)
                    {
                        if (dl.OrderNumber.Equals(order.OrderNumber))
                        {
                            OrderMatchedUI deal = new OrderMatchedUI();
                            deal.TimeStamp = dl.TimeStamp.Substring(0, 2) + ":" + dl.TimeStamp.Substring(2, 2) + ":" + dl.TimeStamp.Substring(4, 2);
                            deal.OrderNumber = dl.OrderNumber;
                            deal.ConfirmNumber = dl.ConfirmNumber;
                            deal.Volume = dl.MatchedVolume;
                            deal.Price = dl.MatchedPrice;
                            deal.MAccount = dl.CouterAccount;
                            dealList.Add(deal);
                        }
                    }

                    foreach (ConfirmDealData cdl in cross)
                    {
                        if (cdl.OrderNumber.Equals(order.OrderNumber))
                        {
                            OrderMatchedUI deal = new OrderMatchedUI();
                            deal.TimeStamp = cdl.TimeStamp.Substring(0, 2) + ":" + cdl.TimeStamp.Substring(2, 2) + ":" + cdl.TimeStamp.Substring(4, 2);
                            deal.OrderNumber = cdl.OrderNumber;
                            deal.ConfirmNumber = cdl.ConfirmNumber;
                            deal.Volume = cdl.MatchedVolume;
                            deal.Price = cdl.MatchedPrice;
                            deal.MAccount = cdl.CouterAccount;
                            dealList.Add(deal);
                        }
                    }

                    foreach (ConfirmOrderCancelData cnl in ConfirmCancel)
                        if (cnl.OrderNumber.Equals(order.OrderNumber))
                        {
                            ui.CancelDetail = new OrderCancelUI(cnl.Timestamp, cnl.OrderNumber, cnl.CancelShares, cnl.OrderCancelStatus);
                            if (cnl.OrderCancelStatus.Equals("S"))
                                ui.Status += "A";
                            else
                                ui.Status += "X";
                        }

                    foreach (ConfirmOrderChangeData chng in ConfirmChange)
                    {
                        if (chng.OrderNumber.Equals(order.OrderNumber))
                        {
                            changeList.Add(new HoseOrderChangeUI(chng.Timestamp, chng.OrderNumber, chng.ClientID, chng.PortClientFlag, chng.PublishedVolume, chng.Price));
                            ui.AccountNoChange = chng.ClientID;
                        }
                    }

                    if (changeList.Count > 0)
                        ui.Status += "M";

                    if (dealList.Count > 0)
                    {
                        foreach (OrderMatchedUI dl in dealList)
                        {
                            ui.MVolume += dl.Volume;
                            ui.MValue += dl.Volume * dl.Price * 1000;
                        }
                        if (ui.MVolume.Equals(ui.Volume))
                            ui.Status += (ui.Status.IndexOf("P") > -1) ? ui.Status.Replace("P", "F") : "F";
                        else
                            ui.Status += "P";
                    }


                    ui.AveragePrice = (ui.MVolume.Equals(0)) ? 0 : ui.MValue / ui.MVolume / 1000;
                    ui.MatchedDetail = dealList;
                    ui.ChangeDetail = changeList;
                    list.Add(ui);
                }

                return list;
            }
            catch (System.Exception e)
            {
                throw e;
            }

        }

        public List<OrderUI> getHastcOrders()
        {
            try
            {
                MortgageMornitorDAL dac = new MortgageMornitorDAL();
                List<OrderUI> list = new List<OrderUI>();

                List<STSORDERS> stsOrder = dac.getSTS_ORDERS();
                List<STSTRADING_RESULT> stsResult = dac.getSTS_TRADING_RESULT();
                List<SecuritiesInfo> stockInfo = dac.getSTOCKSINFO();

                foreach (SecuritiesInfo item in stockInfo)
                    if (!stocks.ContainsKey(item.StockId))
                        stocks.Add(item.StockId, item);


                foreach (STSORDERS order in stsOrder)
                {
                    OrderUI ui = new OrderUI();
                    List<OrderMatchedUI> dealList = new List<OrderMatchedUI>();
                    List<HoseOrderChangeUI> changeList = new List<HoseOrderChangeUI>();

                    ui.AccountNo = order.ACCOUNT_NO;
                    ui.OrderNo = order.ORDER_NO;
                    ui.AccountNoChange = "";
                    ui.Status = "";
                    ui.Side = (order.OORB.Equals(1)) ? "MUA" : "BÁN";
                    if (stocks.ContainsKey(Convert.ToInt32(order.STOCK_ID)))
                        ui.Symbol = stocks[Convert.ToInt32(order.STOCK_ID)].Symbol.Trim();
                    else
                        ui.Symbol = "TRAIPHIEU";
                    ui.Time = order.ORDER_TIME.Substring(0, order.ORDER_TIME.Length - 4);
                    ui.Volume = Convert.ToInt64(order.ORDER_QTTY);
                    ui.Price = (order.ORDER_PRICE / 1000).ToString("N1");
                    ui.Market = "HASTC";

                    if (!order.QUOTE_PRICE.Equals(0))
                        ui.PriceChange = (order.ORDER_PRICE.Equals(order.QUOTE_PRICE)) ? String.Empty : (order.QUOTE_PRICE / 1000).ToString("N1");
                    else
                    {
                        ui.PriceChange = string.Empty;
                        ui.Status += "X";
                    }


                    foreach (STSTRADING_RESULT rst in stsResult)
                    {
                        if (order.ORDER_NO.Equals(rst.B_ORDER_NO))
                            dealList.Add(new OrderMatchedUI(rst.MATCH_TIME.Substring(0, rst.MATCH_TIME.Length - 4), rst.B_ORDER_NO, rst.CONFIRM_NO, Convert.ToInt64(rst.QUANTITY), rst.PRICE / 1000, rst.S_ACCOUNT_NO));
                        else if (order.ORDER_NO.Equals(rst.S_ORDER_NO))
                            dealList.Add(new OrderMatchedUI(rst.MATCH_TIME.Substring(0, rst.MATCH_TIME.Length - 4), rst.S_ORDER_NO, rst.CONFIRM_NO, Convert.ToInt64(rst.QUANTITY), rst.PRICE / 1000, rst.B_ACCOUNT_NO));
                    }

                    if (dealList.Count > 0)
                        foreach (OrderMatchedUI dl in dealList)
                        {
                            ui.MVolume += dl.Volume;
                            ui.MValue += dl.Volume * dl.Price * 1000;
                        }

                    ui.AveragePrice = (ui.MVolume.Equals(0)) ? 0 : (ui.MValue / ui.MVolume / 1000);

                    if (!order.QUOTE_PRICE.Equals(0))
                        if (!order.ORDER_PRICE.Equals(order.QUOTE_PRICE))
                            ui.Status += "M";

                    if (ui.MVolume.Equals(ui.Volume))
                        ui.Status += (ui.Status.IndexOf("P") > -1) ? ui.Status.Replace("P", "F") : "F";
                    else if (ui.MVolume > 0)
                        ui.Status += "P";

                    ui.MatchedDetail = dealList;
                    list.Add(ui);
                }
                return list;
            }
            catch (System.Exception e)
            {
                throw e;
            }
        }

        public List<OrderUI> getHosePtOrders()
        {
            try
            {
                List<OrderUI> list = new List<OrderUI>();
                MortgageMornitorDAL dac = new MortgageMornitorDAL();

                List<OFPTDealData> OFPT = dac.getOFPTDealData();
                List<TFPTDealData> TFPT = dac.getTFPTDealData();
                List<ConfirmPtDealData> ConfirmPtDeal = dac.getConfirmPtDealData();
                List<ConfirmPtDealCancelData> ConfirmPtDealCancel = dac.getConfirmPtDealCancelData();
                List<PtDealReplyData> PtReply = dac.getPtDealReplyData();
                List<PtACKData> PtACK = dac.getPtACKData();

                //                 foreach (OFPTDealData ofpt in OFPT)
                //                 {
                //                     OrderUI ui = new OrderUI();
                //                     List<OrderMatchedUI> dealList = new List<OrderMatchedUI>();
                //                     List<HoseOrderChangeUI> changeList = new List<HoseOrderChangeUI>();
                // 
                //                     ui.AccountNo = ofpt.ClientIDSeller;
                //                     ui.Side = "BÁN";
                //                     ui.Symbol = ofpt.SecuritySymbol.Trim();
                //                     ui.Time = ofpt.Timestamp;
                //                     ui.MVolume = ofpt.BrokerPortfolioVolBuyer + ofpt.BrokerClientVolBuyer + ofpt.MutualFundVolBuyer + ofpt.BrokerForeignVolBuyer;
                // 
                //                     dealList.Add(new OrderMatchedUI(ofpt.Timestamp, ofpt.deal.Timestamp, deal.DealID, deal.ConfirmNumber, Convert.ToInt64(deal.Volume), Convert.ToDecimal(deal.Price) / 1000000, ofpt.ClientIDBuyer));
                // 
                //                     foreach (ConfirmPtDealCancelData cnl in ConfirmPtDealCancel)
                //                     {
                //                         if (cnl.ReplyCode.Equals("C") && cnl.ConfirmNumber.Equals(deal.ConfirmNumber))
                //                         {
                //                             ui.CancelDetail.Timestamp = cnl.Timestamp.Substring(0, 2) + ":" + cnl.Timestamp.Substring(2, 2) + ":" + cnl.Timestamp.Substring(4, 2);
                //                             ui.CancelDetail.OrderCancelStatus = "C";
                //                             ui.CancelDetail.CancelShares = Convert.ToInt64(deal.Volume);
                //                             ui.CancelDetail.OrderNumber = deal.DealID;
                //                         }
                //                     }
                //                     ui.MValue = ui.MVolume * ui.AveragePrice * 1000;
                // 
                //                     list.Add(ui);
                //                 }

                foreach (ConfirmPtDealData deal in ConfirmPtDeal)
                {
                    OrderUI ui = new OrderUI();
                    List<OrderMatchedUI> dealList = new List<OrderMatchedUI>();
                    List<HoseOrderChangeUI> changeList = new List<HoseOrderChangeUI>();
                    List<OrderMatchedUI> dealList2 = new List<OrderMatchedUI>();

                    ui.OrderNo = deal.ConfirmNumber;
                    ui.Price = (Convert.ToDecimal(deal.Price) / 1000000).ToString("N1");
                    ui.Volume = Convert.ToInt64(deal.Volume);
                    ui.Time = deal.Timestamp.Substring(0, 2) + ":" + deal.Timestamp.Substring(2, 2) + ":" + deal.Timestamp.Substring(4, 2);

                    ui.MVolume = ui.Volume;
                    ui.AveragePrice = Convert.ToDecimal(deal.Price) / 1000000;
                    ui.MValue = ui.MVolume * ui.AveragePrice * 1000;

                    //                     ui.Side = (deal.Side.Equals("S")) ? "BÁN" : "MUA";
                    ui.Market = "HOSE";

                    foreach (OFPTDealData ofpt in OFPT)
                    {
                        if (ofpt.DealID.Equals(deal.DealID) && deal.Side.Trim().Equals("X"))
                        {
                            ui.AccountNo = ofpt.ClientIDSeller;
                            ui.Side = "BÁN";
                            ui.Symbol = ofpt.SecuritySymbol.Trim();
                            ui.Time = ofpt.Timestamp;

                            dealList.Add(new OrderMatchedUI(deal.Timestamp, deal.DealID, deal.ConfirmNumber, Convert.ToInt64(deal.Volume), Convert.ToDecimal(deal.Price) / 1000000, ofpt.ClientIDBuyer));

                            foreach (ConfirmPtDealCancelData cnl in ConfirmPtDealCancel)
                            {
                                if (cnl.ReplyCode.Equals("C") && cnl.ConfirmNumber.Equals(deal.ConfirmNumber))
                                {
                                    ui.CancelDetail.Timestamp = cnl.Timestamp.Substring(0, 2) + ":" + cnl.Timestamp.Substring(2, 2) + ":" + cnl.Timestamp.Substring(4, 2);
                                    ui.CancelDetail.OrderCancelStatus = "C";
                                    ui.CancelDetail.CancelShares = Convert.ToInt64(deal.Volume);
                                    ui.CancelDetail.OrderNumber = deal.DealID;
                                }
                            }
                            ui.MValue = ui.MVolume * ui.AveragePrice * 1000;
                        }

                        if (ui.CancelDetail == null)
                            ui.Status = "F";
                        else
                            ui.Status = "X";

                        if (deal.Side.Trim().Equals("X"))
                        {
                            dealList2.Add(new OrderMatchedUI(deal.Timestamp, deal.DealID, deal.ConfirmNumber, Convert.ToInt64(deal.Volume), Convert.ToDecimal(deal.Price) / 1000000, ofpt.ClientIDSeller));

                            ui.ChangeDetail = changeList;
                            ui.MatchedDetail = dealList2;

                            //list.Add(new OrderUI(ui.Time, ui.OrderNo, ofpt.ClientIDBuyer, ui.AccountNoChange, "MUA", ui.Symbol, ui.Volume, ui.Price, ui.Status, ui.PriceChange, ui.MVolume, ui.AveragePrice, ui.MValue, ui.ChangeDetail, dealList2, ui.CancelDetail, "HOSE"));
                            //break;
                        }
                    }


                    foreach (PtACKData ack in PtACK)
                    {
                        if (deal.ConfirmNumber.Equals(ack.ConfirmNumber))
                        {
                            OrderMatchedUI match = new OrderMatchedUI();
                            ui.Symbol = ack.SecuritySymbol.Trim();
                            ui.Side = "MUA";

                            match.ConfirmNumber = ack.ConfirmNumber;
                            match.MAccount = ack.ContraFirmS;
                            match.OrderNumber = ack.ConfirmNumber;
                            match.TimeStamp = ack.Timestamp.Substring(0, 2) + ":" + ack.Timestamp.Substring(2, 2) + ":" + ack.Timestamp.Substring(4, 2);
                            match.Price = Convert.ToDecimal(ack.Price) / 1000000;
                            match.Volume = Convert.ToInt64(ack.Volume);


                            foreach (PtDealReplyData reply in PtReply)
                            {
                                if (reply.ConfirmNumber.Equals(ack.ConfirmNumber))
                                {
                                    ui.AccountNo = reply.ClientIDB.Trim();
                                    if (reply.ReplyCode.Equals("C"))
                                        ui.Status = "X";
                                    else
                                        ui.Status = "F";
                                }
                            }
                            dealList.Add(match);
                        }
                    }


                    foreach (TFPTDealData tfpt in TFPT)
                    {
                        if (tfpt.DealID.Equals((deal.DealID)))
                        {
                            ui.AccountNo = tfpt.ClientIDSeller;
                            ui.Side = "BÁN";
                            ui.Symbol = tfpt.SecuritySymbol;
                            ui.Time = tfpt.TimeStamp;

                            dealList.Add(new OrderMatchedUI(deal.Timestamp, deal.DealID, deal.ConfirmNumber, Convert.ToInt64(deal.Volume), Convert.ToDecimal(deal.Price) / 1000000, string.Empty));

                            foreach (ConfirmPtDealCancelData cnl in ConfirmPtDealCancel)
                            {
                                if (cnl.ReplyCode.Equals("C") && cnl.ConfirmNumber.Equals(deal.ConfirmNumber))
                                {
                                    ui.CancelDetail.Timestamp = cnl.Timestamp.Substring(0, 2) + ":" + cnl.Timestamp.Substring(2, 2) + ":" + cnl.Timestamp.Substring(4, 2);
                                    ui.CancelDetail.OrderCancelStatus = "C";
                                    ui.CancelDetail.CancelShares = Convert.ToInt64(deal.Volume);
                                    ui.CancelDetail.OrderNumber = deal.DealID;
                                }
                            }
                            ui.MValue = ui.MVolume * ui.AveragePrice * 1000;
                        }
                        if (ui.CancelDetail == null)
                            ui.Status = "F";
                        else
                            ui.Status = "X";

                    }

                    ui.MatchedDetail = dealList;
                    ui.ChangeDetail = changeList;
                    list.Add(ui);
                }

                return list;
            }
            catch (System.Exception e)
            {
                throw e;
            }
        }

        public List<OrderUI> getHastcPtOrders()
        {
            try
            {
                MortgageMornitorDAL dac = new MortgageMornitorDAL();
                List<OrderUI> list = new List<OrderUI>();

                List<STSTRADING_RESULT> stsResult = dac.getSTS_TRADING_RESULT();

                foreach (STSTRADING_RESULT rst in stsResult)
                {
                    if (rst.NORP.Equals(2))
                    {
                        OrderUI ui = new OrderUI();
                        List<OrderMatchedUI> dealList = new List<OrderMatchedUI>();
                        List<HoseOrderChangeUI> changeList = new List<HoseOrderChangeUI>();

                        ui.AccountNo = (rst.B_CODE_TRADE.Equals("59")) ? rst.B_ACCOUNT_NO : rst.S_ACCOUNT_NO;
                        ui.OrderNo = rst.S_ORDER_NO;
                        ui.AccountNoChange = "";
                        ui.Status = "F";
                        ui.Side = (rst.B_CODE_TRADE.Equals("59")) ? "MUA" : "BÁN";
                        ui.Symbol = rst.SEC_CODE.Trim();
                        ui.Time = rst.MATCH_TIME.Substring(0, rst.MATCH_TIME.Length - 4);
                        ui.Volume = Convert.ToInt64(rst.QUANTITY);
                        ui.Price = (rst.PRICE / 1000).ToString("N1");
                        ui.PriceChange = string.Empty;
                        ui.Market = "HASTC";
                        dealList.Add(new OrderMatchedUI(rst.MATCH_TIME, ui.OrderNo, rst.CONFIRM_NO, Convert.ToInt64(rst.QUANTITY), rst.PRICE / 1000, (rst.B_CODE_TRADE.Equals("59")) ? rst.S_ACCOUNT_NO : rst.B_ACCOUNT_NO));
                        ui.MVolume = Convert.ToInt64(rst.QUANTITY);
                        ui.MValue = rst.QUANTITY * rst.PRICE;
                        ui.AveragePrice = (ui.MVolume.Equals(0)) ? 0 : (ui.MValue / ui.MVolume / 1000);
                        ui.MatchedDetail = dealList;
                        list.Add(ui);
                    }
                }
                return list;
            }
            catch (System.Exception e)
            {
                throw e;
            }

        }


        public List<OrderUI> getHoseOrdersSummary(DateTime from, DateTime to)
        {
            try
            {
                MortgageMornitorDAL dac = new MortgageMornitorDAL();
                List<OrderUI> list = new List<OrderUI>();

                List<OrderNewData> OrderNew = dac.getBackupNewConditionedOrderData(from, to);
                List<OrderChangeData> OrderChange = dac.getBackupOrderChangeData(from, to);
                List<OrderCancelData> OrderCancel = dac.getBackupOrderCancelData(from, to);

                List<ConfirmOrderChangeData> ConfirmChange = dac.getBackupConfirmOrderChangeData(from, to);
                List<ConfirmCrossingDealData> ConfirmCross = dac.getBackupConfirmCrossingDealData(from, to);
                List<ConfirmDealData> ConfirmDeal = dac.getBackupConfirmDealData(from, to);
                List<ConfirmOrderCancelData> ConfirmCancel = dac.getBackupConfirmOrderCancelData(from, to);

                List<ConfirmDealData> cross = new List<ConfirmDealData>();
                foreach (ConfirmCrossingDealData cr in ConfirmCross)
                {
                    ConfirmDealData confirm = new ConfirmDealData();
                    confirm.TimeStamp = cr.Timestamp;
                    confirm.OrderNumber = cr.OrderNumberB;
                    confirm.Side = "B";
                    confirm.MatchedPrice = cr.Price;
                    confirm.MatchedVolume = cr.Volume;
                    confirm.CouterAccount = cr.OrderNumberS;
                    confirm.ConfirmNumber = cr.ConfirmNumber;
                    cross.Add(confirm);
                }
                foreach (ConfirmCrossingDealData cr in ConfirmCross)
                {
                    ConfirmDealData confirm = new ConfirmDealData();
                    confirm.TimeStamp = cr.Timestamp;
                    confirm.OrderNumber = cr.OrderNumberS;
                    confirm.Side = "S";
                    confirm.MatchedPrice = cr.Price;
                    confirm.MatchedVolume = cr.Volume;
                    confirm.CouterAccount = cr.OrderNumberB;
                    confirm.ConfirmNumber = cr.ConfirmNumber;
                    cross.Add(confirm);
                }


                foreach (OrderNewData order in OrderNew)
                {
                    OrderUI ui = new OrderUI();
                    List<OrderMatchedUI> dealList = new List<OrderMatchedUI>();
                    List<HoseOrderChangeUI> changeList = new List<HoseOrderChangeUI>();

                    ui.Time = order.TimeStamp.Substring(0, 2) + ":" + order.TimeStamp.Substring(2, 2) + ":" + order.TimeStamp.Substring(4, 2);
                    ui.OrderNo = order.OrderNumber;
                    ui.AccountNo = order.ClientID;
                    ui.Side = (order.Side.Equals("S")) ? "BÁN" : "MUA";
                    ui.Symbol = order.Symbol.Trim();
                    ui.Volume = order.Volume;
                    ui.Price = order.Price.Trim();
                    ui.Status = string.Empty;
                    ui.Market = "HOSE";
                    ui.TransDate = order.TransDate;

                    foreach (ConfirmDealData dl in ConfirmDeal)
                    {
                        if (dl.OrderNumber.Equals(order.OrderNumber) && dl.TransDate.Equals(order.TransDate))
                        {
                            OrderMatchedUI deal = new OrderMatchedUI();
                            deal.TimeStamp = dl.TimeStamp.Substring(0, 2) + ":" + dl.TimeStamp.Substring(2, 2) + ":" + dl.TimeStamp.Substring(4, 2);
                            deal.OrderNumber = dl.OrderNumber;
                            deal.ConfirmNumber = dl.ConfirmNumber;
                            deal.Volume = dl.MatchedVolume;
                            deal.Price = dl.MatchedPrice;
                            deal.MAccount = dl.CouterAccount;
                            dealList.Add(deal);
                        }
                    }

                    foreach (ConfirmDealData cdl in cross)
                    {
                        if (cdl.OrderNumber.Equals(order.OrderNumber) && cdl.TransDate.Equals(order.TransDate))
                        {
                            OrderMatchedUI deal = new OrderMatchedUI();
                            deal.TimeStamp = cdl.TimeStamp.Substring(0, 2) + ":" + cdl.TimeStamp.Substring(2, 2) + ":" + cdl.TimeStamp.Substring(4, 2);
                            deal.OrderNumber = cdl.OrderNumber;
                            deal.ConfirmNumber = cdl.ConfirmNumber;
                            deal.Volume = cdl.MatchedVolume;
                            deal.Price = cdl.MatchedPrice;
                            deal.MAccount = cdl.CouterAccount;
                            dealList.Add(deal);
                        }
                    }

                    foreach (ConfirmOrderCancelData cnl in ConfirmCancel)
                        if (cnl.OrderNumber.Equals(order.OrderNumber) && cnl.TransDate.Equals(order.TransDate))
                        {
                            ui.CancelDetail = new OrderCancelUI(cnl.Timestamp, cnl.OrderNumber, cnl.CancelShares, cnl.OrderCancelStatus);
                            if (cnl.OrderCancelStatus.Equals("S"))
                                ui.Status += "A";
                            else
                                ui.Status += "X";
                        }

                    foreach (ConfirmOrderChangeData chng in ConfirmChange)
                    {
                        if (chng.OrderNumber.Equals(order.OrderNumber) && chng.TransDate.Equals(order.TransDate))
                        {
                            changeList.Add(new HoseOrderChangeUI(chng.Timestamp, chng.OrderNumber, chng.ClientID, chng.PortClientFlag, chng.PublishedVolume, chng.Price));
                            ui.AccountNoChange = chng.ClientID;
                        }
                    }

                    if (changeList.Count > 0)
                        ui.Status += "M";

                    if (dealList.Count > 0)
                    {
                        foreach (OrderMatchedUI dl in dealList)
                        {
                            ui.MVolume += dl.Volume;
                            ui.MValue += dl.Volume * dl.Price * 1000;
                        }
                        if (ui.MVolume.Equals(ui.Volume))
                            ui.Status += (ui.Status.IndexOf("P") > -1) ? ui.Status.Replace("P", "F") : "F";
                        else
                            ui.Status += "P";
                    }


                    ui.AveragePrice = (ui.MVolume.Equals(0)) ? 0 : ui.MValue / ui.MVolume / 1000;
                    ui.MatchedDetail = dealList;
                    ui.ChangeDetail = changeList;
                    list.Add(ui);
                }

                return list;
            }
            catch (System.Exception e)
            {
                throw e;
            }

        }

        public List<OrderUI> getHastcOrdersSummary(DateTime from, DateTime to)
        {
            try
            {
                MortgageMornitorDAL dac = new MortgageMornitorDAL();
                List<OrderUI> list = new List<OrderUI>();

                List<STSORDERS> stsOrder = dac.getSTS_ORDERSBackup(from, to);
                List<STSTRADING_RESULT> stsResult = dac.getSTS_TRADING_RESULTBackup(from, to);
                List<SecuritiesInfo> stockInfo = dac.getSTOCKSINFOBackup(from, to);

                foreach (SecuritiesInfo item in stockInfo)
                    if (!stocks.ContainsKey(item.StockId))
                        stocks.Add(item.StockId, item);


                foreach (STSORDERS order in stsOrder)
                {
                    OrderUI ui = new OrderUI();
                    List<OrderMatchedUI> dealList = new List<OrderMatchedUI>();
                    List<HoseOrderChangeUI> changeList = new List<HoseOrderChangeUI>();

                    ui.AccountNo = order.ACCOUNT_NO;
                    ui.OrderNo = order.ORDER_NO;
                    ui.AccountNoChange = "";
                    ui.Status = "";
                    ui.Side = (order.OORB.Equals(1)) ? "MUA" : "BÁN";
                    ui.Symbol = stocks[Convert.ToInt32(order.STOCK_ID)].Symbol.Trim();
                    ui.Time = order.ORDER_TIME.Substring(0, order.ORDER_TIME.Length - 4);
                    ui.Volume = Convert.ToInt64(order.ORDER_QTTY);
                    ui.Price = (order.ORDER_PRICE / 1000).ToString("N1");
                    ui.Market = "HASTC";
                    ui.TransDate = order.ORDER_DATE;

                    if (!order.QUOTE_PRICE.Equals(0))
                        ui.PriceChange = (order.ORDER_PRICE.Equals(order.QUOTE_PRICE)) ? String.Empty : (order.QUOTE_PRICE / 1000).ToString("N1");
                    else
                    {
                        ui.PriceChange = string.Empty;
                        ui.Status += "X";
                    }


                    foreach (STSTRADING_RESULT rst in stsResult)
                    {
                        if (order.ORDER_NO.Equals(rst.B_ORDER_NO) && order.ORDER_DATE.Equals(rst.TRADING_DATE))
                            dealList.Add(new OrderMatchedUI(rst.MATCH_TIME.Substring(0, rst.MATCH_TIME.Length - 4), rst.B_ORDER_NO, rst.CONFIRM_NO, Convert.ToInt64(rst.QUANTITY), rst.PRICE / 1000, rst.S_ACCOUNT_NO));
                        else if (order.ORDER_NO.Equals(rst.S_ORDER_NO) && order.ORDER_DATE.Equals(rst.TRADING_DATE))
                            dealList.Add(new OrderMatchedUI(rst.MATCH_TIME.Substring(0, rst.MATCH_TIME.Length - 4), rst.S_ORDER_NO, rst.CONFIRM_NO, Convert.ToInt64(rst.QUANTITY), rst.PRICE / 1000, rst.B_ACCOUNT_NO));
                    }

                    if (dealList.Count > 0)
                        foreach (OrderMatchedUI dl in dealList)
                        {
                            ui.MVolume += dl.Volume;
                            ui.MValue += dl.Volume * dl.Price * 1000;
                        }

                    ui.AveragePrice = (ui.MVolume.Equals(0)) ? 0 : (ui.MValue / ui.MVolume / 1000);

                    if (!order.QUOTE_PRICE.Equals(0))
                        if (!order.ORDER_PRICE.Equals(order.QUOTE_PRICE))
                            ui.Status += "M";

                    if (ui.MVolume.Equals(ui.Volume))
                        ui.Status += (ui.Status.IndexOf("P") > -1) ? ui.Status.Replace("P", "F") : "F";
                    else if (ui.MVolume > 0)
                        ui.Status += "P";

                    ui.MatchedDetail = dealList;
                    list.Add(ui);
                }
                return list;
            }
            catch (System.Exception e)
            {
                throw e;
            }
        }

        public List<OrderUI> getHosePtOrders(DateTime from, DateTime to)
        {
            try
            {
                List<OrderUI> list = new List<OrderUI>();
                MortgageMornitorDAL dac = new MortgageMornitorDAL();

                List<OFPTDealData> OFPT = dac.getOFPTDealData();
                List<TFPTDealData> TFPT = dac.getTFPTDealData();
                List<ConfirmPtDealData> ConfirmPtDeal = dac.getConfirmPtDealData();
                List<ConfirmPtDealCancelData> ConfirmPtDealCancel = dac.getConfirmPtDealCancelData();
                List<PtDealReplyData> PtReply = dac.getPtDealReplyData();
                List<PtACKData> PtACK = dac.getPtACKData();


                foreach (ConfirmPtDealData deal in ConfirmPtDeal)
                {
                    OrderUI ui = new OrderUI();
                    List<OrderMatchedUI> dealList = new List<OrderMatchedUI>();
                    List<HoseOrderChangeUI> changeList = new List<HoseOrderChangeUI>();
                    List<OrderMatchedUI> dealList2 = new List<OrderMatchedUI>();

                    ui.OrderNo = deal.ConfirmNumber;
                    ui.Price = (Convert.ToDecimal(deal.Price) / 1000000).ToString("N1");
                    ui.Volume = Convert.ToInt64(deal.Volume);
                    ui.Time = deal.Timestamp.Substring(0, 2) + ":" + deal.Timestamp.Substring(2, 2) + ":" + deal.Timestamp.Substring(4, 2);

                    ui.MVolume = ui.Volume;
                    ui.AveragePrice = Convert.ToDecimal(deal.Price) / 1000000;
                    ui.MValue = ui.MVolume * ui.AveragePrice * 1000;

                    //                     ui.Side = (deal.Side.Equals("S")) ? "BÁN" : "MUA";
                    ui.Market = "HOSE";

                    foreach (OFPTDealData ofpt in OFPT)
                    {
                        if (ofpt.DealID.Equals(deal.DealID) && deal.Side.Trim().Equals("X"))
                        {
                            ui.AccountNo = ofpt.ClientIDSeller;
                            ui.Side = "BÁN";
                            ui.Symbol = ofpt.SecuritySymbol.Trim();
                            ui.Time = ofpt.Timestamp;

                            dealList.Add(new OrderMatchedUI(deal.Timestamp, deal.DealID, deal.ConfirmNumber, Convert.ToInt64(deal.Volume), Convert.ToDecimal(deal.Price) / 1000000, ofpt.ClientIDBuyer));

                            foreach (ConfirmPtDealCancelData cnl in ConfirmPtDealCancel)
                            {
                                if (cnl.ReplyCode.Equals("C") && cnl.ConfirmNumber.Equals(deal.ConfirmNumber))
                                {
                                    ui.CancelDetail.Timestamp = cnl.Timestamp.Substring(0, 2) + ":" + cnl.Timestamp.Substring(2, 2) + ":" + cnl.Timestamp.Substring(4, 2);
                                    ui.CancelDetail.OrderCancelStatus = "C";
                                    ui.CancelDetail.CancelShares = Convert.ToInt64(deal.Volume);
                                    ui.CancelDetail.OrderNumber = deal.DealID;
                                }
                            }
                            ui.MValue = ui.MVolume * ui.AveragePrice * 1000;
                        }

                        if (ui.CancelDetail == null)
                            ui.Status = "F";
                        else
                            ui.Status = "X";

                        if (deal.Side.Trim().Equals("X"))
                        {
                            dealList2.Add(new OrderMatchedUI(deal.Timestamp, deal.DealID, deal.ConfirmNumber, Convert.ToInt64(deal.Volume), Convert.ToDecimal(deal.Price) / 1000000, ofpt.ClientIDSeller));

                            ui.ChangeDetail = changeList;
                            ui.MatchedDetail = dealList2;
                        }
                    }


                    foreach (PtACKData ack in PtACK)
                    {
                        if (deal.ConfirmNumber.Equals(ack.ConfirmNumber))
                        {
                            OrderMatchedUI match = new OrderMatchedUI();
                            ui.Symbol = ack.SecuritySymbol.Trim();
                            ui.Side = "MUA";

                            match.ConfirmNumber = ack.ConfirmNumber;
                            match.MAccount = ack.ContraFirmS;
                            match.OrderNumber = ack.ConfirmNumber;
                            match.TimeStamp = ack.Timestamp.Substring(0, 2) + ":" + ack.Timestamp.Substring(2, 2) + ":" + ack.Timestamp.Substring(4, 2);
                            match.Price = Convert.ToDecimal(ack.Price) / 1000000;
                            match.Volume = Convert.ToInt64(ack.Volume);


                            foreach (PtDealReplyData reply in PtReply)
                            {
                                if (reply.ConfirmNumber.Equals(ack.ConfirmNumber))
                                {
                                    ui.AccountNo = reply.ClientIDB.Trim();
                                    if (reply.ReplyCode.Equals("C"))
                                        ui.Status = "X";
                                    else
                                        ui.Status = "F";
                                }
                            }
                            dealList.Add(match);
                        }
                    }


                    foreach (TFPTDealData tfpt in TFPT)
                    {
                        if (tfpt.DealID.Equals((deal.DealID)))
                        {
                            ui.AccountNo = tfpt.ClientIDSeller;
                            ui.Side = "BÁN";
                            ui.Symbol = tfpt.SecuritySymbol;
                            ui.Time = tfpt.TimeStamp;

                            dealList.Add(new OrderMatchedUI(deal.Timestamp, deal.DealID, deal.ConfirmNumber, Convert.ToInt64(deal.Volume), Convert.ToDecimal(deal.Price) / 1000000, string.Empty));

                            foreach (ConfirmPtDealCancelData cnl in ConfirmPtDealCancel)
                            {
                                if (cnl.ReplyCode.Equals("C") && cnl.ConfirmNumber.Equals(deal.ConfirmNumber))
                                {
                                    ui.CancelDetail.Timestamp = cnl.Timestamp.Substring(0, 2) + ":" + cnl.Timestamp.Substring(2, 2) + ":" + cnl.Timestamp.Substring(4, 2);
                                    ui.CancelDetail.OrderCancelStatus = "C";
                                    ui.CancelDetail.CancelShares = Convert.ToInt64(deal.Volume);
                                    ui.CancelDetail.OrderNumber = deal.DealID;
                                }
                            }
                            ui.MValue = ui.MVolume * ui.AveragePrice * 1000;
                        }
                        if (ui.CancelDetail == null)
                            ui.Status = "F";
                        else
                            ui.Status = "X";

                    }

                    ui.MatchedDetail = dealList;
                    ui.ChangeDetail = changeList;
                    list.Add(ui);
                }

                return list;
            }
            catch (System.Exception e)
            {
                throw e;
            }
        }

        public List<OrderUI> getHastcPtOrders(DateTime from, DateTime to)
        {
            try
            {
                MortgageMornitorDAL dac = new MortgageMornitorDAL();
                List<OrderUI> list = new List<OrderUI>();

                List<STSTRADING_RESULT> stsResult = dac.getSTS_TRADING_RESULT();

                foreach (STSTRADING_RESULT rst in stsResult)
                {
                    if (rst.NORP.Equals(2))
                    {
                        OrderUI ui = new OrderUI();
                        List<OrderMatchedUI> dealList = new List<OrderMatchedUI>();
                        List<HoseOrderChangeUI> changeList = new List<HoseOrderChangeUI>();

                        ui.AccountNo = (rst.B_CODE_TRADE.Equals("59")) ? rst.B_ACCOUNT_NO : rst.S_ACCOUNT_NO;
                        ui.OrderNo = rst.S_ORDER_NO;
                        ui.AccountNoChange = "";
                        ui.Status = "F";
                        ui.Side = (rst.B_CODE_TRADE.Equals("59")) ? "MUA" : "BÁN";
                        ui.Symbol = rst.SEC_CODE.Trim();
                        ui.Time = rst.MATCH_TIME.Substring(0, rst.MATCH_TIME.Length - 4);
                        ui.Volume = Convert.ToInt64(rst.QUANTITY);
                        ui.Price = (rst.PRICE / 1000).ToString("N1");
                        ui.PriceChange = string.Empty;
                        ui.Market = "HASTC";
                        dealList.Add(new OrderMatchedUI(rst.MATCH_TIME, ui.OrderNo, rst.CONFIRM_NO, Convert.ToInt64(rst.QUANTITY), rst.PRICE / 1000, (rst.B_CODE_TRADE.Equals("59")) ? rst.S_ACCOUNT_NO : rst.B_ACCOUNT_NO));
                        ui.MVolume = Convert.ToInt64(rst.QUANTITY);
                        ui.MValue = rst.QUANTITY * rst.PRICE;
                        ui.AveragePrice = (ui.MVolume.Equals(0)) ? 0 : (ui.MValue / ui.MVolume / 1000);
                        ui.MatchedDetail = dealList;
                        list.Add(ui);
                    }
                }
                return list;
            }
            catch (System.Exception e)
            {
                throw e;
            }

        }

        public List<TradingResultUI> getStockNettingInvestorId(decimal investorID, DateTime transdate)
        {
            List<TradingResultUI> list = new List<TradingResultUI>();
            List<AccountDataModel> src = ls_dal.getStockNettingInvestorId(investorID, transdate);
            foreach (AccountDataModel item in src)
            {
                list.Add(new TradingResultUI(item.stockId, string.Empty, item.tradingAmount, 0, null, null, null));
            }
            return list;
        }

        public bool isClearingDone()
        {
            return ls_dal.isClearingDone();
        }

        public AccountData getCustomerInfo(string accountNo)
        {
            try
            {
                return ls_dal.getCustomerInfo(accountNo);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region MortgageDAL
        public void InportLoadRate(LoanRateData item)
        {
            m_dal.ImportLoadRate(item);
        }
        public decimal getLoanRate(DateTime date, string symbol)
        {
            return m_dal.getLoanRate(date, symbol);
        }
        public void DeleteLoanRate(DateTime date)
        {
            m_dal.DeleteLoanRate(date);
        }

        public void InsertMortgageTrans(string accountno, string contractno,
                                    DateTime date, string code, int type, decimal credit, decimal debit)
        {
            m_dal.InsertMortgageTrans(accountno, contractno, date, code, type, credit, debit);
        }

        public void DeleteMortgageTransByContractNo(string contractno)
        {
            m_dal.DeleteMortgageTransByContractNo(contractno);
        }

        public List<MortgageTransUI> getMortgageTransByCode(string contractno)
        {
            List<MortgageTrans> original = m_dal.getMortgageTransByCode(contractno);
            List<MortgageTransUI> list = new List<MortgageTransUI>();

            foreach (MortgageTrans item in original)
                list.Add(new MortgageTransUI(item));
            return list;

        }

        public List<MortgageTransUI> searchMortgageTrans(string code, string accountno, string contractno,
                                                DateTime from, DateTime to, int type,
                                                decimal lowDebit, decimal highDebit,
                                                decimal lowCredit, decimal highCredit)
        {
            List<MortgageTrans> original = m_dal.searchMortgageTrans(code, accountno, contractno,
                                             from, to, type, lowDebit, highDebit, lowCredit, highCredit);
            List<MortgageTransUI> list = new List<MortgageTransUI>();

            foreach (MortgageTrans item in original)
                list.Add(new MortgageTransUI(item));
            return list;

        }

        public decimal getBlockingQttyByCode(string AccountNo, string code)
        {
            return getBlockingQttyByCode(AccountNo, code);
        }

        public decimal getBlockingQttyByCodeAndContract(string AccountNo, string code, string contractno)
        {
            return getBlockingQttyByCodeAndContract(AccountNo, code, contractno);
        }

        public string InsertCustomer(string Name, string Gender, string AccountNo, string IdcardNo, DateTime IdcardDate, string IdcardIssue, string PhoneMobile, string PhoneFix, string Email, string AddressContact, string AddressResident)
        {
            return InsertCustomer(Name, Gender, AccountNo, IdcardNo, IdcardDate, IdcardIssue, PhoneMobile, PhoneFix, Email, AddressContact, AddressResident);
        }
        public string getCustomerIDByAccountNo(string AccountNo)
        {
            return getCustomerIDByAccountNo(AccountNo);
        }

        public AccountUI getCustomerByID(string CustomerID)
        {
            return new AccountUI(m_dal.getCustomerByID(CustomerID));
        }

        public void DeleteCustomerById(string CustomerID)
        {
            m_dal.DeleteCustomerById(CustomerID);
        }

        public List<AccountUI> getCustomers()
        {
            List<AccountUI> list = new List<AccountUI>();
            List<AccountData> src = m_dal.getCustomers();
            foreach (AccountData item in src)
            {
                list.Add(new AccountUI(item));
            }
            return list;
        }

        public int InsertFee(DateTime from, DateTime to, string Name, int type, decimal value, string customerid, string contractno, string accountno)
        {
            return InsertFee(from, to, Name, type, value, customerid, contractno, accountno);
        }
        public FeeData getFeeByCode(string ID)
        {
            return m_dal.getFeeByCode(ID);
        }
        public FeeData getFeeByCodeAndDate(string Code, DateTime date)
        {
            return m_dal.getFeeByCodeAndDate(Code, date);
        }
        public FeeData getFeeByType(int type, string customerid, string contractno, string accountno)
        {
            return m_dal.getFeeByType(type, customerid, contractno, accountno);
        }

        public string InsertContract(string contractno, string customerid, DateTime start, DateTime end, decimal fee, decimal penaltyfee, decimal processfee, int contracttype, string status, decimal contractvalue, string AccountNo, string original)
        {
            return m_dal.InsertContract(contractno, customerid, start, end, fee, penaltyfee, processfee, contracttype, status, contractvalue, AccountNo, original);
        }
        public ContractUI getContractByNo(string contractno)
        {
            ContractData con = m_dal.getContractByNo(contractno);
            AccountData acc = ls_dal.getCustomerInfo(con.AccountNo);
            return new ContractUI(acc, con);
        }
        public List<ContractUI> getcontractByCustomerId(string customerid)
        {
            List<ContractData> original = m_dal.getcontractByCustomerId(customerid);
            List<ContractUI> list = new List<ContractUI>();

            foreach (ContractData item in original)
            {
                AccountData acc = ls_dal.getCustomerInfo(item.AccountNo);
                list.Add(new ContractUI(acc, item));
            }
            return list;
        }
        public List<ContractUI> getContractByDate(DateTime from, DateTime to)
        {
            List<ContractData> original = m_dal.getContractByDate(from, to);
            List<ContractUI> list = new List<ContractUI>();

            foreach (ContractData item in original)
            {
                AccountData acc = ls_dal.getCustomerInfo(item.AccountNo);
                list.Add(new ContractUI(acc, item));
            }
            return list;
        }
        public List<ContractUI> getContractByValue(decimal from, decimal to)
        {
            List<ContractData> original = m_dal.getContractByValue(from, to);
            List<ContractUI> list = new List<ContractUI>();

            foreach (ContractData item in original)
            {
                AccountData acc = ls_dal.getCustomerInfo(item.AccountNo);
                list.Add(new ContractUI(acc, item));
            }
            return list;
        }
        public List<ContractUI> searchContract(string contractno, string customerid,
                                            DateTime from, DateTime to, decimal lowvalue,
                                            decimal highvalue, int contracttype,
                                            string status, string AccountNo, string originalContract)
        {
            List<ContractData> original = m_dal.searchContract(contractno, customerid,
                                             from, to, lowvalue,
                                             highvalue, contracttype,
                                             status, AccountNo, originalContract);
            List<ContractUI> list = new List<ContractUI>();

            foreach (ContractData item in original)
            {
                AccountData acc = ls_dal.getCustomerInfo(item.AccountNo);
                list.Add(new ContractUI(acc, item));
            }
            return list;
        }

        public void InsertCustomerAccount(string customerId, string accounts)
        {
            m_dal.InsertCustomerAccount(customerId, accounts);
        }
        public List<string> getCustomerAccounts(string customerId)
        {
            return m_dal.getCustomerAccounts(customerId);
        }
        public void deleteCustomerAccount(string customerId)
        {
            m_dal.deleteCustomerAccount(customerId);
        }

        public decimal GetAccLoanByAccountNo(string AccountNo)
        {
            return m_dal.GetAccumulateLoanByAccountNo(AccountNo);
        }
        public void UpdateAccumulateLoan(string AccountNo, decimal AccuValue, DateTime LastUpdate)
        {
            m_dal.UpdateAccumulateLoan(AccountNo, AccuValue, LastUpdate);
        }

        #endregion
    }
}
